import sortedcontainers
class Solution(object):
    def longestSubarray(self, nums, limit):
        left = 0
        right = 0
        n = len(nums)
        st = sortedcontainers.SortedList()
        max_len = 0
        while right < n:
            st.add(nums[right])
            if st[-1] - st[0] <= limit:
                max_len = max(max_len, len(st))
            else:
                while st[-1] - st[0] > limit:
                    st.remove(nums[left])
                    left += 1
            right += 1
        return max_len


